package cn.itcast.activemq.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**消息消费者(点对点)*/
public class ConsumerTest {
    public static void main(String[] args) throws Exception {
        //定义连接消息中间件的地址:tcp协议
        String borkerURL= "tcp://192.168.12.131:61616";
        //创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(borkerURL);
        //创建连接对象
        Connection connection = connectionFactory.createConnection();
        //开始连接
        connection.start();

        /**创建会话对象*/
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        //创建目标消息队列
        Destination topic = session.createTopic("test-topic");
        //创建消息消费者
        MessageConsumer consumer = session.createConsumer(topic);
        //设置消息监听器
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                //判断消息类型
                if (message instanceof TextMessage){
                    //强制转换
                    TextMessage tm = (TextMessage) message;
                    //获取消息内容
                    try {
                        System.out.println(tm.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
